package cn.kgc.service.impl;


import cn.kgc.base.BaseInfoProperties;
import cn.kgc.entity.CandFollowHrMo;
import cn.kgc.repository.CandFollowHrRepository;
import cn.kgc.service.CandFollowHrService;
import cn.kgc.utils.RedisUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wangyue
 * @version 1.0
 * 求职者关注HR的相关业务层
 */
@Service
public class CandFollowHrServiceImpl implements CandFollowHrService {

    @Resource
    private CandFollowHrRepository candFollowHrRepository;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean addCandFollowHr(CandFollowHrMo candFollowHo) {
        String candUserId = candFollowHo.getCandUserId();
        String hrId = candFollowHo.getHrId();
        // 判断求职者是否关注Hr，已经关注返回false
        if (candFollowHrRepository.countByHrIdAndCandUserId(hrId, candUserId) == 0) {
            return false;
        }
        // 设置关注的时间
        candFollowHo.setCreataedDate(new Date());
        // 记录求职者关注的HR的信息
        candFollowHrRepository.insert(candFollowHo);
        // 统计求职者关注多少HR 没有高并发 数据过期时间15天
        String key = BaseInfoProperties.REDIS_CAND_FOLLOW_HR_COUNT + ":" + candUserId;
        if (!redisUtil.hasKey(key)) {
            int count = candFollowHrRepository.countByCandUserId(candUserId);
            redisUtil.set(key, count, 15, TimeUnit.DAYS);
        }
        // 求职者关注的HR数量+1
        redisUtil.increment(key);
        return true;
    }

    /**
     * 并发量不高的情况也可以：
     * 求职者关注HR或者取消HR时,我们也可以在业务层中直接修改数据库中的数据,然后将缓存删除。
     * 回来查询数据时,如通缓存中没有数据可以从数据库中将最新统计数据查询出来放到缓存中。
     */
    @Override
    public void deleteCandFollowHr(String hrId, String candId) {
        candFollowHrRepository.deleteByHrIdAndCandUserId(hrId, candId);
        // 求职者关注的HR数量-1（缓存没数据不修改）
        String key = BaseInfoProperties.REDIS_CAND_FOLLOW_HR_COUNT + ":" + candId;
        if (redisUtil.hasKey(key)) {
            redisUtil.decrement(key);
        }
    }

    @Override
    public List<CandFollowHrMo> page(String candUserId, int pageIndex, int pageSize) {
        Pageable pageable = PageRequest.of(pageIndex - 1, pageSize);
        return candFollowHrRepository.findByCandUserIdOrderByCreataedDateDesc(candUserId, pageable);
    }

    @Override
    public boolean hasFollowedHr(String candUserId, String hrId) {
        return false;
    }
}
